package org.pr.ddddesigner.infrastructure.helper;

import com.xw.soonmanager.commons.helper.ReactiveFileHelper;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.function.BodyExtractors;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.UriBuilder;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.util.List;
import java.util.function.Function;

/**
 * @author chenbin
 */
public class ReactiveHttpHelper {
    private ReactiveHttpHelper() throws IllegalAccessException {
        throw new IllegalAccessException();
    }

    public static Mono<Void> download(String url, Path target) {
        return WebClient.create()
                .get()
                .uri(url)
                .exchangeToMono(exchanger(target));
    }

    public static Mono<Void> download(Function<UriBuilder, URI> uriFunction, Path target) {
        return WebClient.create()
                .get()
                .uri(uriFunction)
                .exchangeToMono(exchanger(target));
    }

    private static Function<ClientResponse, Mono<Void>> exchanger(final Path target) {
        return response -> {
            if (response.statusCode().is3xxRedirection()) {
                List<String> locationHeader = response.headers().header(HttpHeaders.LOCATION);
                if (locationHeader.size() > 0) {
                    String location = locationHeader.get(0);
                    if (StringUtils.hasText(location)) {
                        return download(location, target);
                    }
                }
            }

            Flux<ByteBuffer> body = response.body(BodyExtractors.toDataBuffers())
                    .map(DataBuffer::asByteBuffer);

            return ReactiveFileHelper.copy(body, target);
        };
    }
}
